package com.linkage.jz.bankruptcy.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.PDFViewActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProPublicDetailActivity;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.bean.TokenInfo;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.user.ImageShowActivity;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Activity基类
 */
public abstract class BaseActivity extends FragmentActivity {
    public static final String KEY_PROJECTID = "project_id";

    protected View titlebar_back, titlebar_menu;
    protected TextView titlebar_title, titlebar_menu_text;

    protected ShapeLoadingDialog mShapeLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        titlebar_back = findViewById(R.id.titlebar_back);
        titlebar_menu = findViewById(R.id.titlebar_menu);
        titlebar_title = findViewById(R.id.titlebar_title);
        titlebar_menu_text = findViewById(R.id.titlebar_menu_text);
        if (titlebar_back != null) {
            titlebar_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }

        mShapeLoadingDialog = new ShapeLoadingDialog(this);

        initView();
        initTitle();
        initData();
        setListener();
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.white));
        //设置状态栏字体颜色为黑色
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);


        //设置状态栏字体颜色为白色
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

    }

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 初始化Title
     */
    public abstract void setListener();

    /**
     * 初始化View
     */
    public abstract void initTitle();

    /**
     * 设置View的相关监听
     */
    public abstract void initView();

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    public void showToast(String msg) {
        ToastUtil.getInstance(this).showShortToast(msg);
    }

    public void showToast(String msg, ToastUtil.TOAST_TYPE toast_type) {
        ToastUtil.getInstance(this).showToast(msg, toast_type);
    }

    public void getToken() {

        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        params.put("appid", Consts.APPID);
        params.put("nonce", rom);
        params.put("timestamp", timestamp);

        String sign = SignUtil.createSign(Consts.APPKEY, params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("sign", sign)
                .build();

        String url = Consts.WEBURL_GETTOKEN;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                String str = "";
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        Gson gson = new Gson();
                        TokenInfo info = gson.fromJson(object.optString("data"), TokenInfo.class);
                        BankruptcyApp.tokeninfo = info;
                        SPUtils.getInstance(Consts.SPNAME).put("tokeninfo", object.optString("data"));

                    }

                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    protected String getUserToken() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        return userToken;
    }

    protected String getUserId() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");
        return userToken;
    }


    public static void openOrDownloadFile(TaskAtta atta, final Activity context){
        String fileName = atta.getAttachmentName();
        String url = atta.getAttachmentWatermarkAddress();
        if(TextUtils.isEmpty(url)){
            url = atta.getAttachmentPreviewAddress();
        }
        if(TextUtils.isEmpty(url)){
            url = atta.getAttachmentDownloadAddress();
        }
//        final String url = (String) atta.getAttachmentDownloadAddress();
        if (TextUtils.equals(FileUtil.getMIMEType(fileName), "image/*")) {
            ImageShowActivity.start(context, url,
                    ImageShowActivity.FROM_SINGLE_SHOW);
        } else if (TextUtils.equals(FileUtil.getMIMEType(fileName),
                "application/pdf")) {
            Intent intent = new Intent(context, PDFViewActivity.class);
            intent.putExtra("url", url);
            context.startActivity(intent);
        } else {
            Uri uri = Uri.parse(url);
            Dialog tipDialog = new AlertDialog
                    .Builder(context)
                    .setTitle("提示")
                    .setMessage("当前文件不支持直接预览，是否下载并打开？")
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            final Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.setData(uri);
                            context.startActivity(intent);
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create();

            tipDialog.setCancelable(false);
            tipDialog.show();
        }
    }


    protected void showLoading(String text) {
        mShapeLoadingDialog.setLoadingText(text);
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();
    }

    protected void hideLoading() {
        if(null != mShapeLoadingDialog) {
            mShapeLoadingDialog.dismiss();
        }
    }
}
